
import redis
import os.path

class RemoteQueue(object):

	def __init__(self,name="rss",u='localhost',p=6379):
		self.cache = redis.StrictRedis(host=u, port=p)
		self.name = name

	def put(self,vs):
		if self.size() > 819200:
			return
		if len(vs) == 0:
			return
		self.cache.lpush(self.name,*vs)

	def size(self):
		return self.cache.llen(self.name)

	def clear(self):
		i = 0
		j = self.size()
		self.cache.ltrim(self.name,j+1,i)

	#def pop_one(self):
	#	return self.cache.lpop(self.name)

	def pop(self,n=8192):
		i = 0
		j = self.size()
		if j > n:
			i = j-n
		vs = self.cache.lrange(self.name, i, j)
		self.cache.ltrim(self.name,j+1,0)
		return vs

##############################################################################

def init_data(filename):
	qs = list()
	with open(filename) as f:
		for line in f:
			v = line.strip().decode('utf-8')
			qs.append(v)
	return qs

def save_data(qs,filename):
	with open(filename,mode='w') as f:
		for v in qs:
			line = v.encode('utf-8')+'\n'
			f.write(line)

class LocalQueue(object):

	def __init__(self,location):
		if os.path.exists(location):
			self.Q = init_data(location)
		else:
			self.Q = list()
		self.location = location

	def put(self,vs):
		if self.size() > 819200:
			return
		if len(vs) == 0:
			return
		self.Q.extend(vs)
		with open(self.location,mode='a') as f:
			vs = [v.encode('utf-8') for v in vs]
			text = '\n'.join(vs)+'\n'
			f.write(text)

	def size(self):
		return len(self.Q)

	def pop(self):
		vs = [v for v in self.Q]
		self.Q = list()
		save_data(self.Q,self.location)
		return vs



if __name__ == '__main__':

	print 'test'

	def test1():
		rq = LocalQueue('Qs.txt')

		vs = ["1","2","3"]
		rq.put(vs)

	def test2():
		rq = LocalQueue('Qs.txt')

		vs = rq.pop()
		print vs

	#test1()
	test2()

